/**
 * Created by zy on 2017/4/18.
 */
+function ($) {
    'use strict';

    let callback = {
            beforeSend: null,
            success: null,
            error: null,
            complete: null
        },
        ajax = {
            type: 'POST',
            async: true,
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            data: {},
            timeout: 1000 * 90,
            dataType: 'JSON',
            beforeSend: callback.beforeSend,
            success: callback.success,
            error: callback.error,
            complete: callback.error
        },
        url = {
            login: 'http://thisa:8888/login_kyfw',
            vCode: {
                submit: 'http://thisa:8888/submit_vcode',
                refresh: 'http://thisa:8888/refresh_vcode'
            },
            passengers: {
                get: 'http://thisa:8888/get_passengers',
                add: 'http://thisa:8888/add_passenger'
            },
            check_order: 'http://thisa:8888/check_order',
            submit_order: 'http://thisa:8888/submit_order',
            stopTicketing: 'http://thisa:8888/stop_grabticket',
            cancel_order: 'http://thisa:8888/cancel_order',
            queryTrain: 'http://thisa:8888/query_train',
            pem: 'http://thisa:8888/static/pubkey.pem'
        },
        doAjax = function (params) {
            // 跨域配置
            $.support.cors = true;
            return $.ajax($.extend({}, ajax, params));
        };

    $.fn.ticket = {
        url: url,
        doAjax: function (params) {
            return doAjax(params);
        },
        login: function (params = {}) {
            let username, password, options = $.extend({}, {}, ajax);
            options['url'] = url.login;

            if (params['username'] && params['password']) {
                username = params['username'];
                password = params['password'];

            } else if (sessionStorage.username !== undefined && sessionStorage.password !== undefined) {
                username = sessionStorage.username;
                password = sessionStorage.password;
            } else {
                return $.alert('无法登录', '参数错误');
            }

            options['data'] = {
                account: username,
                pwd: password
            };

            // 运行前函数
            options.beforeSend = function () {
                $.showLoading('登录中');
                if (typeof  params.beforeSend === 'function') {
                    params.beforeSend();
                }
            };

            // 成功函数
            options.success = function (resb) {
                $.hideLoading();
                if (resb.step === 1) {
                    // 渲染认证码
                    $('body').append(
                        `<div id="code">
                          <div class="train-mask"></div>
                          <div class="auth">
                            <div class="center">
                              <img src="${resb.data.filename}" id="vcode_img">
                              <a href="javascript:void(0);" class="weui-btn" id="img_refresh">
                                <i class="icon iconfont icon-svg27"></i>刷新
                              </a>
                              <div class="auth-check">
                                <label for="1">
                                  <input type="checkbox" id="1">
                                    <i class="icon iconfont icon-huochepiao"></i>
                                </label>
                                <label for="2">
                                  <input type="checkbox" id="2">
                                  <i class="icon iconfont icon-huochepiao"></i>
                                </label>
                                <label for="3">
                                  <input type="checkbox" id="3">
                                  <i class="icon iconfont icon-huochepiao"></i>
                                </label>
                                <label for="4">
                                  <input type="checkbox" id="4">
                                  <i class="icon iconfont icon-huochepiao"></i>
                                </label>
                              </div>
                              <div class="auth-check">
                                <label for="5">
                                  <input type="checkbox" id="5">
                                  <i class="icon iconfont icon-huochepiao"></i>
                                </label>
                                <label for="6">
                                  <input type="checkbox" id="6">
                                  <i class="icon iconfont icon-huochepiao"></i>
                                </label>
                                <label for="7">
                                  <input type="checkbox" id="7">
                                  <i class="icon iconfont icon-huochepiao"></i>
                                </label>
                                <label for="8">
                                  <input type="checkbox" id="8">
                                  <i class="icon iconfont icon-huochepiao"></i>
                                </label>
                              </div>
                              <div class="weui-btn-area">
                                <a href="javascript:void(0);" class="weui-btn btn_or" id="vCode">确定</a>
                              </div>
                            </div>
                          </div>
                        </div>`.trim());

                    $(document)
                    // 验证码提交
                        .on('click', '#vCode', function () {
                            let $inputs = $(this).parents('.center').find(':checked'),
                                code = $.map($inputs, function (input) {
                                    return $(input).attr('id');
                                }).join(' ');
                            return doAjax({
                                url: url.vCode.submit,
                                data: {vcode: code},
                                beforeSend: function () {
                                    $.showLoading();
                                },
                                success: function (resp) {
                                    $.hideLoading();
                                    switch (Number(resp.error)) {
                                        case 0:
                                            //TODO 李宁后台未完成数据封装
                                            if (resp.step === 1) {
                                                $('#vcode_img').attr('src', resp.data['filename']);
                                                $.alert('验证码错误，请重新选择', function () {
                                                    $(':checked').removeAttr('checked');
                                                });
                                            }

                                            if (resp.step === -1) {
                                                // 设置login与登录超时
                                                sessionStorage.setItem('login', true);
                                                sessionStorage.setItem('_login_exp_', Date.parse(new Date()) + 10 * 60 * 1000);
                                                sessionStorage.setItem('has_logged', true);
                                                $('#code').remove();

                                                $.alert("登录成功", function () {
                                                    sessionStorage.removeItem('userList');
                                                    sessionStorage.removeItem('passengers');
                                                    $('#bound').addClass('hide');
                                                    $('#logged,#modify').removeClass('hide');
                                                    $('#modify').find('dd.weui-flex__item').addClass('color-orange');
                                                    $('#logged').find('.weui-flex__item').text(username);

                                                    if (params['refresh']) {
                                                        return window.location.reload();
                                                    }
                                                });
                                            }
                                            break;
                                        case 6:
                                            $.alert('网络错误');
                                            break;
                                        case 7:
                                            $.alert('超时');
                                            break;
                                        case 18:
                                            $('#vcode_img').attr('src', resp.data['filename']);
                                            $.alert('验证码错误，请重新选择', function () {
                                                $(':checked').removeAttr('checked');
                                            });
                                            break;
                                        case 19:
                                            $.alert('帐号/密码错误');
                                            break;
                                        default:
                                            $.alert('登录失败');
                                    }
                                    // if (resp.step === 1) {
                                    //     $('#vcode_img').attr('src', resp.data['filename']);
                                    //     $.alert('验证码错误，请重新选择', '失败', function () {
                                    //         $(':checked').removeAttr('checked');
                                    //     });
                                    // }
                                    // else if (resp.step === -1) {
                                    //     // 设置login与登录超时
                                    //     sessionStorage.setItem('login', true);
                                    //     sessionStorage.setItem('_login_exp_', Date.parse(new Date()) + 10 * 60 * 1000);
                                    //     sessionStorage.setItem('has_logged', true);
                                    //     $('#code').remove();
                                    //
                                    //     $.alert("登陆成功", function () {
                                    //         sessionStorage.removeItem('userList');
                                    //         sessionStorage.removeItem('passengers');
                                    //         $('#bound').addClass('hide');
                                    //         $('#logged,#modify').removeClass('hide');
                                    //         $('#modify').find('dd.weui-flex__item').addClass('color-orange');
                                    //         $('#logged').find('.weui-flex__item').text(ticket.storage.get('username'));
                                    //
                                    //         if (params['refresh']) {
                                    //             return window.location.reload();
                                    //         }
                                    //     });
                                    // }
                                    console.log(resp);
                                },
                                error: function (xhr) {
                                    $.hideLoading();
                                    $.alert(xhr.statusText, '错误', function () {
                                        $('#code').remove();
                                    });
                                }
                            });
                        })

                        // 验证码刷新
                        .on('click', '#img_refresh', function () {
                            $(':checked').removeAttr('checked');
                            return doAjax({
                                url: url.vCode.refresh,
                                xhrFields: {
                                    withCredentials: true
                                },
                                crossDomain: true,
                                beforeSend: function () {
                                    $.showLoading();
                                },
                                success: function (resb) {
                                    if (resb.error === 1) {
                                        $.alert(resb.info);
                                    } else {
                                        $('#vcode_img').attr('src', resb.data['filename']);
                                    }
                                },
                                error: function (xhr) {
                                    $.alert(xhr.statusText);
                                },
                                complete: function () {
                                    $.hideLoading();
                                }
                            });
                        })
                }
                if (typeof  params.success === 'function') {
                    params.success(resb);
                }
            };

            // 错误函数
            options.error = function (xhr) {
                $.alert(xhr.statusText, '绑定失败', function () {
                    $.hideLoading();
                    if (typeof  params.success === 'function') {
                        params.error(xhr);
                    }
                });
            };

            // 执行
            doAjax(options);
        },
        cacheTrain: function () {
            // 参数判断
            sessionStorage.removeItem('data');
            let paras = JSON.parse(sessionStorage.getItem('paras')),
                info = JSON.parse(sessionStorage.getItem('infos'));
            if (!paras || !info) {
                return $.alert('参数错误', '缓存车次信息失败', function () {
                    window.location.reload();
                });
            }

            // 执行
            doAjax({
                url: url.queryTrain,
                async: false,
                data: {
                    fromStation: paras.from_station_name,
                    toStation: paras.to_station_name,
                    startDate: info.startDate
                },
                success: function (resp) {
                    sessionStorage.setItem('data', JSON.stringify(resp.data));
                }
            });
        },
        storage: {
            set: function (key, value, exp = undefined) {
                let timestamp = Date.parse(new Date());
                if (typeof value === 'string' && value.constructor === String) {
                    sessionStorage.setItem(key, value);
                } else {
                    sessionStorage.setItem(key, JSON.stringify(value));
                }
                if (Number.isInteger(exp)) {
                    sessionStorage.setItem(`_${key}_exp_`, timestamp + exp);
                }
            },
            get: function (key) {
                let value = sessionStorage[key],
                    exp = Number(sessionStorage[`_${key}_exp_`]),
                    timestamp = Date.parse(new Date());
                if (value) {
                    if (exp && exp <= timestamp) {
                        sessionStorage.removeItem(key);
                        sessionStorage.removeItem(`_${key}_exp_`);
                        return undefined;
                    }

                    try {
                        return JSON.parse(value);
                    } catch (err) {
                        return value;
                    }
                } else {
                    return undefined;
                }
            },
            getAll: function () {
                var allData = {};
                $.each(sessionStorage, function (key, value) {
                    try {
                        allData[key] = JSON.parse(value);
                    } catch (err) {
                        allData[key] = value;
                    }
                });
                return allData;
            },
            clear: function () {
                return sessionStorage.clear();
            },
            remove: function (list) {
                if (!list instanceof Array) {
                    return false;
                }

                $.each(list, function () {
                    sessionStorage.removeItem(this);
                });
                return true;
            }
        }
    }
}(jQuery);